package com.xiaoye.qbproject.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoye.qbproject.domain.SubjectZb;
import com.xiaoye.qbproject.domain.ZbInfo;
import com.xiaoye.qbproject.mapper.SubjectZbMapper;
import com.xiaoye.qbproject.service.SubjectZbService;
import com.xiaoye.qbproject.vo.SubjectZbVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【SUBJECT_ZB(专题与装备关联表)】的数据库操作Service实现
 * @createDate 2025-02-11 15:38:16
 */
@Service
public class SubjectZbServiceImpl extends ServiceImpl<SubjectZbMapper, SubjectZb>
        implements SubjectZbService {
    @Autowired
    private SubjectZbMapper subjectZbMapper;

    /**
     * @param subjectZbVo
     * @description: 查询对应的装备信息
     * @author: ChenYao
     * @return: com.xiaoye.qbproject.domain.ZbInfo
     * @ceateDate: 2025/2/11 下午4:28
     */
    @Override
    public List<ZbInfo> getZbListOfSubjectZb(SubjectZbVo subjectZbVo) {
        List<ZbInfo> zbInfoList = subjectZbMapper.getZbListOfSubjectZb(subjectZbVo);
        return zbInfoList;
    }

    /**
     * @param subjectZbVo
     * @description: 添加专题与装备关联信息
     * @author: ChenYao
     * @return: void
     * @ceateDate: 2025/2/11 下午5:09
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addSubjectZb(SubjectZbVo subjectZbVo) {
        // 获取专题 关联对的所有装备id
        List<String> oldZbIds = subjectZbMapper.getZbIdsBySubjectId(subjectZbVo.getSubjectId());

        List<String> zbIds = subjectZbVo.getZbIds();
        // 与新的装备id进行去重 保留新的装备id
        List<String> addZbIds = zbIds.stream()
                .filter(zbId -> !oldZbIds.contains(zbId))
                .collect(Collectors.toList()
                );
        if (addZbIds.isEmpty()) {
            throw new RuntimeException("添加了重复关联信息");
        }
        // 添加新的装备id到数据库中
        addZbIds.forEach(zbId -> {
            SubjectZb subjectZb = new SubjectZb();
            subjectZb.setSubjectId(subjectZbVo.getSubjectId());
            subjectZb.setZbId(zbId);
            this.save(subjectZb);
        });
    }
}




